package com.kum.service;

import com.aliyun.oss.model.OSSObjectSummary;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kum.mapper.LevelsMapper;
import com.kum.mapper.UserMapper;
import com.kum.pojo.User;
import com.kum.service.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service
public class UserService {

    private static UserMapper userMapper;
    private static LevelsMapper levelsMapper;
    private final OSSClient ossClient;

    @Autowired
    public UserService(OSSClient ossClient, UserMapper userMapper, LevelsMapper levelsMapper) {
        this.ossClient = ossClient;
        this.userMapper = userMapper;
        this.levelsMapper = levelsMapper;
    }

    public static String getUserId(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return userMapper.selectList(wrapper).get(0).getId();
    }


    public static int getUserLevel(String userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", userId);
        return userMapper.selectByMap(map).get(0).getLevel();
    }

    public static long getLevelSpace(int level) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("level", level);
        return Long.valueOf(levelsMapper.selectByMap(map).get(0).getSize()) * 1048576;
    }

    public long getSpaceSize(String userId) {

        long allSize = 0L;
        List<OSSObjectSummary> fileList = ossClient.getAllFileList(userId);
        for (OSSObjectSummary sum :
                fileList) {
            allSize += sum.getSize();
        }
        return allSize;
    }

    public long getSurplusSpace(String userId) {
        int level = getUserLevel(userId);
        long allSpace = getLevelSpace(level);
        long useSpace = getSpaceSize(userId);

        return allSpace - useSpace;


    }


}
